// pages/cart/index.js
const MoneyUtils = require('../../utils/money.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0, // 导航栏总高度
    contentTop: 0, // 内容区域top位置
    cartItems: [], // 购物车商品列表
    selectedItems: [], // 选中的商品ID列表
    totalPrice: 0, // 总价
    totalQuantity: 0, // 总数量
    isAllSelected: false, // 是否全选
    isEditMode: false, // 是否编辑模式
    bottomSafeArea: 0, // 底部安全区域高度
    loading: true // 加载状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 20
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null
    const navBarContentHeight = menuButtonInfo ? (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height : 44
    const navBarHeight = statusBarHeight + navBarContentHeight
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      bottomSafeArea
    })
    
    // 加载购物车数据
    this.loadCartData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次显示页面时重新加载购物车数据
    this.loadCartData()
  },

  /**
   * 加载购物车数据
   */
  async loadCartData() {
    try {
      this.setData({ loading: true })
      
      // 检查登录状态
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      if (!isLoggedIn) {
        wx.showModal({
          title: '需要登录',
          content: '请先登录后查看购物车',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/index'
              })
            } else {
              wx.navigateBack()
            }
          }
        })
        return
      }

      // 调用云函数获取购物车数据
      const result = await wx.cloud.callFunction({
        name: 'getCartItems',
        data: {}
      })

      if (result.result && result.result.success) {
        const cartItems = result.result.data || []
        this.setData({
          cartItems,
          selectedItems: [], // 重置选中状态
          isAllSelected: false
        })
        
        // 计算总价和数量
        this.calculateTotal()
      } else {
        console.error('获取购物车数据失败：', result.result?.message)
        wx.showToast({
          title: '获取购物车数据失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载购物车数据失败：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 选择/取消选择商品
   */
  toggleSelectItem(e) {
    const itemId = e.currentTarget.dataset.id
    const selectedItems = [...this.data.selectedItems]
    const index = selectedItems.indexOf(itemId)
    
    if (index > -1) {
      selectedItems.splice(index, 1)
    } else {
      selectedItems.push(itemId)
    }
    
    const isAllSelected = selectedItems.length === this.data.cartItems.length && this.data.cartItems.length > 0
    
    this.setData({
      selectedItems,
      isAllSelected
    })
    
    this.calculateTotal()
  },

  /**
   * 全选/取消全选
   */
  toggleSelectAll() {
    const isAllSelected = !this.data.isAllSelected
    const selectedItems = isAllSelected ? this.data.cartItems.map(item => item._id) : []
    
    this.setData({
      isAllSelected,
      selectedItems
    })
    
    this.calculateTotal()
  },

  /**
   * 修改商品数量
   */
  async updateQuantity(e) {
    const { id, action } = e.currentTarget.dataset
    const cartItems = [...this.data.cartItems]
    const itemIndex = cartItems.findIndex(item => item._id === id)
    
    if (itemIndex === -1) return
    
    const item = cartItems[itemIndex]
    let newQuantity = item.quantity
    
    if (action === 'increase') {
      newQuantity += 1
    } else if (action === 'decrease') {
      newQuantity = Math.max(1, newQuantity - 1)
    }
    
    if (newQuantity === item.quantity) return
    
    try {
      wx.showLoading({
        title: '更新中...',
        mask: true
      })
      
      // 调用云函数更新数量
      const result = await wx.cloud.callFunction({
        name: 'updateCartItem',
        data: {
          itemId: id,
          quantity: newQuantity
        }
      })
      
      if (result.result && result.result.success) {
        cartItems[itemIndex].quantity = newQuantity
        this.setData({ cartItems })
        this.calculateTotal()
      } else {
        wx.showToast({
          title: result.result?.message || '更新失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('更新商品数量失败：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  /**
   * 删除商品
   */
  async removeItem(e) {
    const itemId = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要从购物车中删除该商品吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '删除中...',
              mask: true
            })
            
            // 调用云函数删除商品
            const result = await wx.cloud.callFunction({
              name: 'removeCartItem',
              data: {
                itemId: itemId
              }
            })
            
            if (result.result && result.result.success) {
              // 从本地数据中移除
              const cartItems = this.data.cartItems.filter(item => item._id !== itemId)
              const selectedItems = this.data.selectedItems.filter(id => id !== itemId)
              const isAllSelected = selectedItems.length === cartItems.length && cartItems.length > 0
              
              this.setData({
                cartItems,
                selectedItems,
                isAllSelected
              })
              
              this.calculateTotal()
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } else {
              wx.showToast({
                title: result.result?.message || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('删除商品失败：', error)
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  /**
   * 批量删除选中商品
   */
  async batchRemove() {
    if (this.data.selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要删除的商品',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的 ${this.data.selectedItems.length} 件商品吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '删除中...',
              mask: true
            })
            
            // 调用云函数批量删除
            const result = await wx.cloud.callFunction({
              name: 'batchRemoveCartItems',
              data: {
                itemIds: this.data.selectedItems
              }
            })
            
            if (result.result && result.result.success) {
              // 重新加载购物车数据
              await this.loadCartData()
              
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
            } else {
              wx.showToast({
                title: result.result?.message || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('批量删除失败：', error)
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  /**
   * 计算总价和数量
   */
  calculateTotal() {
    const { cartItems, selectedItems } = this.data
    let totalPrice = 0
    let totalQuantity = 0
    
    cartItems.forEach(item => {
      if (selectedItems.includes(item._id)) {
        const itemPrice = MoneyUtils.formatAmount(item.price)
        const itemTotal = MoneyUtils.multiply(itemPrice, item.quantity)
        totalPrice = MoneyUtils.add(totalPrice, itemTotal)
        totalQuantity += item.quantity
      }
    })
    
    this.setData({
      totalPrice: MoneyUtils.formatAmount(totalPrice),
      totalQuantity
    })
  },

  /**
   * 切换编辑模式
   */
  toggleEditMode() {
    this.setData({
      isEditMode: !this.data.isEditMode,
      // 不再清空选中状态，保留用户体验
      isAllSelected: this.data.selectedItems.length === this.data.cartItems.length && this.data.cartItems.length > 0
    })
    this.calculateTotal()
  },

  /**
   * 结算
   */
  checkout() {
    if (this.data.selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      })
      return
    }
    
    // 获取选中的商品信息
    const selectedCartItems = this.data.cartItems.filter(item => 
      this.data.selectedItems.includes(item._id)
    )
    
    // 转换为订单格式，确保金额精度
    const orderItems = selectedCartItems.map(item => ({
      productId: item.productId,
      name: item.name,
      price: MoneyUtils.formatAmount(item.price),
      basePrice: MoneyUtils.formatAmount(item.basePrice || item.price),
      quantity: item.quantity,
      image: item.image,
      specifications: item.specifications,
      selectedSpec: item.selectedSpec,
      cartItemId: item._id // 保存购物车项ID，用于后续清理
    }))
    
    // 跳转到订单创建页面
    wx.navigateTo({
      url: `/pages/order_create/index?orderData=${encodeURIComponent(JSON.stringify(orderItems))}&fromCart=true`
    })
  },

  /**
   * 继续购物
   */
  continueShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    await this.loadCartData()
    wx.stopPullDownRefresh()
  },

  /**
   * 返回按钮点击事件
   */
  handleBack() {
    wx.navigateBack()
  }
})